package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        socket = new Socket(serverIp, serverPort);
    }

    private void start(){
        System.out.println("客户端启动！");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner in = new Scanner(System.in);
            PrintWriter writer = new PrintWriter(outputStream);
            Scanner reader = new Scanner(inputStream);

            while(true){
                System.out.print("-> ");
                // 1. 等待用户输入请求
                if(!in.hasNext()){
                    break;
                }
                String request = in.next();
                // 2. 发送请求到服务器
                writer.println(request);
                writer.flush();
                // 3. 等待服务器响应
                String response = reader.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
